package www.ld.com.service;

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import www.ld.com.dictionary.UserStatusEnum;
import www.ld.com.domain.R;
import www.ld.com.domain.dto.PersonalInfoDTO;
import www.ld.com.domain.dto.user.UserInfoDTO;
import www.ld.com.feign.UserFeignService;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service("userDetailsService")
public class CustomerUserDetailsService implements UserDetailsService {
    @Resource
    private UserFeignService userFeignService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        R<UserInfoDTO> r = userFeignService.getPersonalByUsername(username);
        UserInfoDTO userInfoDTO= r.getData();
        return getUserDetails((userInfoDTO));
    }

    /**
     * 获取登录用户信息
     * @param userInfoDTO 用户信息
     * @return
     */
    private UserDetails getUserDetails(UserInfoDTO userInfoDTO)
    {
        List<SimpleGrantedAuthority> authorities = userInfoDTO.getAuthorities().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
       return  new PersonalInfoDTO(
               userInfoDTO.getId(),
               userInfoDTO.getName(),
               userInfoDTO.getUsername(),
               userInfoDTO.getPassword(),
               userInfoDTO.getStatus()!= UserStatusEnum.DISABLE,
               true,
               true,
               userInfoDTO.getStatus()!= UserStatusEnum.LOCKED,
               authorities);
    }

}
